package com.hxzy.controller.admin.employee;

import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.resp.PageResp;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.admin.dicttype.req.DictTypeReq;
import com.hxzy.controller.admin.dicttype.resp.DictTypeResp;
import com.hxzy.controller.admin.employee.req.EmployeeAddReq;
import com.hxzy.controller.admin.employee.req.EmployeeEditReq;
import com.hxzy.controller.admin.employee.req.EmployeeReq;
import com.hxzy.controller.admin.employee.resp.EmployeeResp;
import com.hxzy.controller.admin.mapstruct.DictTypeConvert;
import com.hxzy.controller.admin.mapstruct.EmployeeConvert;
import com.hxzy.entity.Employee;
import com.hxzy.entity.SysDictType;
import com.hxzy.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * @Desc 描述
 * @Author: admin
 * @Date: 2023/06/30/14:30
 */
@Api(tags = "管理后台-管理员列表")
@RestController
@RequestMapping(value = "/api/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService  employeeService;


    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R<PageResp<EmployeeResp>> search(EmployeeReq req){
        PageInfo<Employee>  pageInfo=this.employeeService.search(req);

        //自定义对象
        PageResp<EmployeeResp>  resp=new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setRows(EmployeeConvert.INSTANCE.convert(pageInfo.getList()));

       return R.okHasData(resp);
    }

    @ApiOperation(value = "新增")
    @PostMapping
    public R add(@RequestBody @Valid EmployeeAddReq req){
        if(!req.getLoginPwd().equals(req.getLoginPwdConfirm())){
            return R.build(AckCode.SET_PASSWORD_INVALID);
        }

        //复制对象
        Employee entity = EmployeeConvert.INSTANCE.convert(req);
        //密码加密
        String pwd= BCrypt.hashpw(entity.getLoginPwd());
        entity.setLoginPwd(pwd);

        //新增用户时间
        entity.setCreateTime(new Date());
        entity.setCreateBy(WaimaiThreadLocal.getName());

        boolean save = this.employeeService.save(entity);

        return save? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R<EmployeeResp> findById(@PathVariable(value = "id") Long id){
        if(Objects.isNull(id) || id.intValue()<=0){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        Employee db = this.employeeService.getById(id);
        if(Objects.isNull(db)){
            return R.build(AckCode.DATA_NOT_FOUND);
        }

        //转换
        return R.okHasData( EmployeeConvert.INSTANCE.convert(db));
    }

    @ApiOperation(value = "修改")
    @PutMapping
    public R update(@RequestBody @Valid EmployeeEditReq req){
        if(Objects.isNull(req.getId()) || req.getId().intValue()<=0){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        Employee db = this.employeeService.getById(req.getId());
        if(Objects.isNull(db)){
            return R.build(AckCode.DATA_NOT_FOUND);
        }

        //复制对象
        Employee entity = EmployeeConvert.INSTANCE.convert(req);
        //修改用户时间
        entity.setUpdateTime(new Date());
        entity.setUpdateBy(WaimaiThreadLocal.getName());

        boolean save = this.employeeService.updateById(entity);

        return save? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    /**
     * ids=1,2,3
     * @param ids
     * @return
     */
    @ApiOperation(value = "逻辑删除")
    @DeleteMapping
    public R delete(Long[] ids){
       if(Objects.isNull(ids) || ids.length==0){
           return R.build(AckCode.SYSTEM_PARAM_FAIL);
       }

       boolean result=this.employeeService.delete(ids);
        return result? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }


    @ApiOperation(value = "excel下载")
    @PostMapping(value = "/download")
    public void download(HttpServletResponse response, @RequestBody EmployeeReq req) throws IOException {

        List<Employee> arrList=this.employeeService.download(req);
        List<EmployeeResp> convert = EmployeeConvert.INSTANCE.convert(arrList);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("data", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), EmployeeResp.class).sheet("数据").doWrite(convert);
    }

}
